package com.hgj.blindbox.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hgj.blindbox.entity.BoxItem;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class BlindBoxInitializationService {
    private static final String BOX_ITEMS_KEY = "blindbox:items:";
    private static final String BOX_WEIGHTS_KEY = "blindbox:weights:";
    private static final String BOX_STOCKS_KEY = "blindbox:stocks:";

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 初始化盲盒奖品
     * @param boxId 盲盒ID
     * @param items 奖品列表
     */
    public void initBlindBox(String boxId, List<BoxItem> items) {
        // 删除旧数据
        redisTemplate.delete(BOX_ITEMS_KEY + boxId);
        redisTemplate.delete(BOX_WEIGHTS_KEY + boxId);
        redisTemplate.delete(BOX_STOCKS_KEY + boxId);

        // 使用管道批量操作
//        redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
//            for (BoxItem item : items) {
//                // 存储奖品详情
////                Map<String, String> itemMap = new HashMap<>();
////                itemMap.put("id", item.getId());
////                itemMap.put("name", item.getName());
////                itemMap.put("stock", item.getStock().toString());
////                itemMap.put("weight", item.getWeight().toString());
//
//                try {
//                    connection.hSet(
//                            (BOX_ITEMS_KEY + boxId).getBytes(),
//                            item.getId().getBytes(),
//                            new ObjectMapper().writeValueAsString(item).getBytes()
//                    );
//                } catch (JsonProcessingException e) {
//                    throw new RuntimeException(e);
//                }
//
//                // 存储权重
//                connection.zAdd(
//                        (BOX_WEIGHTS_KEY + boxId).getBytes(),
//                        item.getWeight(),
//                        item.getId().getBytes()
//                );
//
//                // 存储库存
//                connection.hSet(
//                        (BOX_STOCKS_KEY + boxId).getBytes(),
//                        item.getId().getBytes(),
//                        item.getStock().toString().getBytes()
//                );
//            }
//            return null;
//        });

        items.forEach(item->{
            redisTemplate.opsForHash().put(BOX_ITEMS_KEY + boxId,item.getId(), JSONObject.toJSONString(item));
            redisTemplate.opsForZSet().add(BOX_WEIGHTS_KEY + boxId,item.getId(),item.getWeight());
            redisTemplate.opsForHash().put(BOX_STOCKS_KEY + boxId,item.getId(),item.getStock().toString());
        });
    }

    /**
     * 获取盲盒所有奖品信息
     * @param boxId 盲盒ID
     * @return 奖品列表
     */
    public List<BoxItem> getBoxItems(String boxId) {
        Map<Object, Object> itemsMap = redisTemplate.opsForHash()
                .entries(BOX_ITEMS_KEY + boxId);

        return itemsMap.values().stream()
                .map(json -> JSONObject.parseObject(json.toString(),BoxItem.class))
                .collect(Collectors.toList());
    }
}
